<?php
	require_once(dirname(__FILE__).'/route_pattern.php');
	
	class Router {
		private $patterns = array();
		private $default;
		
		function addPattern(RoutePattern $pattern) {
			$this->patterns[] = $pattern;
		}
		
		function extractParameters($path) {
			return $this->findResultFor('extractParameters', $path, $this->default);
		}
		
		public function createPath($parameters) {
			return $this->findResultFor('createPath', $parameters, false);		
		}
		
		private function findResultFor($method, $args, $default) {
			$result = $default;
			$maxMatch = false;
			foreach ($this->patterns as $pattern) {
				$parameters = call_user_func_array(array($pattern, $method), array($args));
				if($parameters !== false) {
					if($maxMatch === false || $pattern->hasHigherPriorityThan($maxMatch)) {
						$maxMatch = $pattern;
						$result = $parameters;
					}
				}
			}
			return $result;
		}
		
		public function setDefaultParameters($default) {
			$this->default = $default;
		}
	}
?>